package com.concurrency.example.atmoic;

import com.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * AtomicReference是引用类型的原子类
 */
@Slf4j
@ThreadSafe
public class AtmoicExample1 {


    public static void main(String[] args) {
        //创建两个对象
        Person p1 = new Person(101);
        Person p2 = new Person(102);

        AtomicReference<Person> ar = new AtomicReference<>(p1);
        //compareAndSet 如果ar值为p1,则把ar的值设为p2
        ar.compareAndSet(p1, p2);

        Person p3 = ar.get();
        log.info("p3:{}", p3);                        //p3:id:102
        log.info("p3.equals(p1):{}",p3.equals(p1));   //p3.equals(p1):false
        log.info("p3.equals(p2):{}",p3.equals(p2));   //p3.equals(p2):true

    }
}

class Person{
    private long id;
    Person(long id){
        this.id = id;
    }
    public String toString(){
        return "id:" + id;
    }
}
